<?php
namespace app\api\controller;
use app\model\ImFriendModel;
use app\model\ImGroupModel;
use app\model\ImGroupUserModel;
use app\model\ImMessageFriendModel;
use app\model\ImMessageGroupModel;
use app\model\ImMessageTypeModel;
use app\model\ImRequestsModel;
use app\model\UserModel;
use support\Request;
use think\facade\Db;
use tool\User;

class ImController extends Base
{
    //添加好友或者群
    public function addImUser(Request $request){
        $type=$request->input('type',0);
        $val=$request->input('val','');
        $user=User::findMe();
        if($type==1){//添加个人为好友
            $toUserId=UserModel::where('phone',$val)->field('id')->find();
            if(!$toUserId){
                e('找不到该用户！');
            }
            if($toUserId['id']==$user['id']){
                e('自己不能添加自己！');
            }
            $find=ImFriendModel::where(function ($query)use ($user,$toUserId){
                $query->where('user_id',$user['id'])->where('friend_id',$toUserId['id']);
            })
            ->whereOr(function ($query) use ($user,$toUserId){
                $query->where('user_id',$toUserId['id'])->where('friend_id',$user['id']);
            })->find();
            if($find){
                e('无需重复添加！');
            }
            $list=[
                ['user_id'=>$user['id'],'friend_id'=>$toUserId['id']],
                ['user_id'=>$toUserId['id'],'friend_id'=>$user['id']]
            ];
           (new ImFriendModel())->saveAll($list);
        }
        if($type==2){//添加到群
            $toUserId=ImGroupModel::where('group_no',$val)->field('id')->find();
            if(!$toUserId){
                e('找不到该群！');
            }
            $find=ImGroupUserModel::where('group_id',$toUserId['id'])->where('user_id',$user['id'])->find();
            if($find){
                e('无需重复添加！');
            }
            ImGroupUserModel::create([
                'group_id'=>$toUserId['id'],
                'user_id'=>$user['id']
            ]);
        }
        s();
    }
    //获取聊天记录
    public function getChatList(Request $request){
        $fromUserId=$request->input('fromUserId',0);
        $toUserId=$request->input('toUserId',0);
        $last_id=$request->input('last_id',0);
        $lei=$request->input('lei','');
        $list=[];
        if($lei=='user'){
            $whereLast=true;
            if($last_id>0){
                $whereLast=[['m.id','<',$last_id]];
            }
            $list=ImMessageFriendModel::alias('m')
                ->leftJoin('im_message_type mt','m.message_type=mt.id')
                ->leftJoin('user u','m.user_id=u.id')
                ->where($whereLast)
                ->where(function ($query2) use ($toUserId,$fromUserId){
                    $query2 ->where(function ($query) use ($toUserId,$fromUserId){
                        $query->where('m.user_id',$toUserId)->where('m.to_user_id',$fromUserId);
                    })->whereOr(function ($query) use ($toUserId,$fromUserId){
                        $query->where('m.user_id',$fromUserId)->where('m.to_user_id',$toUserId);
                    });
                })
                ->order('m.id desc')
                ->field('m.id,m.content,m.create_time,m.extra_info,m.to_user_id as to_id,m.user_id,mt.name as msgType,u.img as toFace,u.name as toName')
                ->limit(20)->select()->toArray();

            ImFriendModel::where('friend_id',$toUserId)->where('user_id',$fromUserId)->update([
                'message_count'=>0,
            ]);
        }
        if($lei=='group'){
            $whereLast=true;
            if($last_id>0){
                $whereLast=[['m.id','<',$last_id]];
            }
            $list=ImMessageGroupModel::alias('m')
                ->leftJoin('im_message_type mt','m.message_type=mt.id')
                ->leftJoin('user u','m.user_id=u.id')
                ->where($whereLast)
                ->where('m.to_group_id',$toUserId)
                ->order('m.id desc')
                ->field('m.id,m.content,m.create_time,m.extra_info,m.to_group_id as to_id,m.user_id,mt.name as msgType,u.img as toFace,u.name as toName')
                ->limit(20)->select()->toArray();
            ImGroupUserModel::where('group_id',$toUserId)->where('user_id',$fromUserId)->update([
                'message_count'=>0
            ]);
        }
        s($list);
    }
    //保存聊天记录
    public function saveChat(Request $request){
        $data=$request->all();
        $message_type=ImMessageTypeModel::where('name',$data['type'])->value('id') ?? 0;
        if($data['type']=='text'){
            $last_message=$data['content'];
        }else{
            $last_message='['.$data['type'].']';
        }
        if($data['lei']=='user'){
            // 私聊
            ImMessageFriendModel::create([
                'user_id'=>$data['fromUserId'],
                'to_user_id'=>$data['toUserId'],
                'content'=>$data['content'],
                'extra_info'=>$data['extra_info'],
                'message_type'=>$message_type,
            ]);
            ImFriendModel::where('user_id',$data['fromUserId'])->update([
                'last_time'=>date('Y-m-d H:i:s'),
                'last_message'=>$last_message,
            ]);
            ImFriendModel::where('friend_id',$data['fromUserId'])->update([
                'last_time'=>date('Y-m-d H:i:s'),
                'last_message'=>$last_message,
                'message_count'=>Db::raw('message_count+1'),
            ]);
        }
        if($data['lei']=='group'){
            // 群聊
            ImMessageGroupModel::create([
                'user_id'=>$data['fromUserId'],
                'to_group_id'=>$data['toUserId'],
                'content'=>$data['content'],
                'extra_info'=>$data['extra_info'],
                'message_type'=>$message_type,
            ]);
            ImGroupUserModel::where('group_id',$data['toUserId'])->update([
                'last_time'=>date('Y-m-d H:i:s'),
                'last_message'=>$last_message,
            ]);
            ImGroupUserModel::where('group_id',$data['toUserId'])->where('user_id','<>',$data['fromUserId'])->update([
                'message_count'=>Db::raw('message_count+1'),
            ]);
        }
        s();
    }
    //获取所有人 getUserListAll
    public function getUserListAll(Request $request){
        $user=User::findMe();
        if(!$user){
            e('请登录后操作！');
        }
        $friendList=ImFriendModel::alias('if')
        ->join('user u','u.id=if.friend_id')
            ->where('if.user_id',$user['id'])
            ->field("u.id,u.name,u.img,if.last_time,if.last_message,'user' as type,if.message_count,if.user_id as toId")
            ->order('if.last_time desc')
            ->select()->toArray();

        $groupList=ImGroupUserModel::alias('igu')
            ->join('im_group ig','igu.group_id=ig.id')
            ->where('user_id',$user['id'])
            ->field("ig.id,ig.img,ig.title as name,igu.last_time,igu.last_message,'group' as type,igu.message_count,igu.group_id as toId")
            ->order('igu.last_time desc')
            ->select()->toArray();
        s([
            'friendList'=>$friendList,
            'groupList'=>$groupList
        ]);
    }

}
